﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Framework.Common.Extention;
using Framework.Data;
using System.Web.Security;
using Dal.Entities;
namespace Web.Controllers
{
    [ValidateInput(false)]
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Login/Details/5
        [HttpPost]
        public ActionResult Index(User user)
        {
            var dbUser = RepositoryFactory.GetRepository().First<User>(i => i.UserName == user.UserName && i.Password == user.Password);
            if (dbUser != null)
            {
                //Session["user"] = dbUser;
                //Session["doctype"] = 1;

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                 1, // 版本
                 dbUser.UserName + "|" + dbUser.ID + "|" + dbUser.Role, // 用户名
                 DateTime.Now, // 票据的签发时间
                 DateTime.Now.AddHours(1), // 票据的过期时间
                 false, // 是否为永久Cookie
                 "1" // 附加的用户数据，此处用来存放用户角色
                );

                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                Response.Cookies.Add(cookie);

                // FormsAuthentication.SetAuthCookie(dbUser.UserName + "|" + dbUser.ID + "|" + dbUser.Role + "|" + 1, true);
                return RedirectToAction("index", "index");
            }
            else
            {
                ViewBag.HasError = false;
            }

            return View();
        }


    }
}
